<script lang="ts" setup>
import { useGlobalDialog } from '@/hooks'
import { type ResultType } from '@/type/type'
import { DialogEnum } from '@/enum'
import { useSystemStore } from '@/stores/system'
import {
  getRoleListApi,
  getRolePermissionMapApi,
  initRoleDTO,
  type RoleDTO,
  type RoleVO,
  roleVO2DOTO,
  updateRoleApi
} from '@/request/api/role'

const { globalDialog } = useGlobalDialog()
const systemStore = useSystemStore()

// 表单
const form = ref<RoleDTO>(initRoleDTO())
const formRef = ref<any>()
/** 查询列表 */
const list = ref<RoleVO[]>([])

const rules = {
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  experience: [{ required: true, message: '经验不能为空', trigger: 'blur' }]
}

const getList = () => {
  getRoleListApi().then((res: ResultType<RoleVO[]>) => {
    list.value = res.data
  })
}

const permissionMap = ref<Map<string, string[]>>(new Map())
const getPermissionList = () => {
  getRolePermissionMapApi().then((res: ResultType<Map<string, string[]>>) => {
    permissionMap.value = res.data
  })
}

/** 修改按钮操作 */
const handleUpdate = (row: RoleVO) => {
  systemStore.dialog.role = true
  form.value = roleVO2DOTO(row)
  permissionForm.value = initPermissionForm()
  permissionDisable.value = initPermissionDisable()
  const permissions = row.permission.split(',')
  for (const permission of permissions) {
    permissionForm.value[permission.split(':')[0]].push(permission)
  }
}

/** 提交按钮 */
function submitForm() {
  form.value.permission = createPermission()
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      return
    }
    await globalDialog('确定修改 ID 为"' + form.value.id + '"的角色?').then((res: boolean) => {
      if (res) {
        console.log(form.value)
        updateRoleApi(form.value).then(() => {
          systemStore.dialog.role = false
          getList()
        })
      }
    })
  })
}

/** 启用停用按钮操作 */
const handleChangeStatus = async (id: number, status: boolean) => {
  const dto: RoleDTO = initRoleDTO()
  dto.id = id
  dto.status = status
  const title = status ? '启用' : '停用'
  await globalDialog('确定' + title + ' ID 为"' + id + '"的角色?').then((res: boolean) => {
    if (res) {
      updateRoleApi(dto).then((res: ResultType<boolean>) => {
        if (res.data) {
          getList()
        }
      })
    }
  })
}

const createPermission = (): string => {
  let permission = ''
  for (const [key, value] of Object.entries(permissionForm.value)) {
    if (value.length > 0) {
      permission += value.join(',') + ','
    }
  }
  return permission.replace(/,$/, '')
}

const initPermissionForm = () => {
  return {
    album: [],
    article: [],
    classify: [],
    comment: [],
    label: [],
    like: [],
    resources: [],
    role: [],
    router: [],
    tree_hole: [],
    user: [],
    website: []
  }
}
const permissionForm = ref<{ [key in string]: string[] }>(initPermissionForm())

const initPermissionDisable = () => {
  return {
    album: false,
    article: false,
    classify: false,
    comment: false,
    label: false,
    like: false,
    resources: false,
    role: false,
    router: false,
    tree_hole: false,
    user: false,
    website: false
  }
}
const permissionDisable = ref<{ [key in string]: boolean }>(initPermissionDisable())

const permissionIDU = ref<{ [key in string]: boolean }>()
/*
 * 如果选中 all 权限，则禁用其他权限
 * 如果全选其他权限，则直接选择 all
 * */
const permissionChange = (k: string) => {
  permissionIDU.value = {
    select: false,
    insert: false,
    update: false,
    delete: false
  }
  for (let i = 0; i < permissionForm.value[k].length; i++) {
    if (permissionForm.value[k][i].toString().includes('all')) {
      permissionForm.value[k] = [k + ':all']
      permissionDisable.value[k] = true
      return
    } else if (permissionForm.value[k][i].toString().includes('insert')) {
      permissionIDU.value['insert'] = true
    } else if (permissionForm.value[k][i].toString().includes('update')) {
      permissionIDU.value['update'] = true
    } else if (permissionForm.value[k][i].toString().includes('delete')) {
      permissionIDU.value['delete'] = true
    }
  }
  if (
    permissionIDU.value['insert'] &&
    permissionIDU.value['update'] &&
    permissionIDU.value['delete']
  ) {
    permissionDisable.value[k] = true
    permissionForm.value[k] = [k + ':all']
  } else {
    permissionDisable.value[k] = false
  }
}

onMounted(() => {
  getList()
  getPermissionList()
})
</script>

<template>
  <el-container class="gap-3" direction="vertical">
    <el-container class="gap-1 pb-2 px-5" direction="vertical">
      <span>角色经验说明 （每天最多 300 经验）：</span>
      <span>万古至尊 (admin)：2^31-1，万古至尊：2^20，千界之主：2^19.5，百劫界王：2^19</span>
      <span
        >造化神境：2^18.5，虚极神境：2^18，掌天神境：2^17.5，归真神境：2^17，十方神境：2^16.5</span
      >
      <span>九天境-武帝：2^16，八荒境-武尊：2^15.5，七宿境-武皇：2^15</span>
      <span
        >六合境-武宗：2^14，五行境-武王：2^13，四象境-武君：2^12，三才境-大武师：2^11，二分境-武师：2^10，一元境-武士：2^9，武徒：2^8</span
      >
    </el-container>
    <el-table :data="list">
      <el-table-column label="ID" prop="id" width="100" />
      <el-table-column label="角色名" prop="name" width="160" />
      <el-table-column label="权限" prop="permission" />
      <el-table-column label="经验值" prop="experience" sortable width="130" />
      <el-table-column label="创建时间" prop="createTime" width="120" />
      <el-table-column label="状态" prop="status" width="70">
        <template #default="scope">
          <el-tag :type="scope.row.status ? 'success' : 'danger'">
            {{ scope.row.status ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="110">
        <template #default="scope">
          <el-button class="!p-2 !m-1" type="primary" @click="handleUpdate(scope.row)">
            <SvgIcon name="edit" />
          </el-button>
          <el-button
            v-if="!scope.row.status"
            class="!p-2 !m-1"
            type="success"
            @click="handleChangeStatus(scope.row.id, true)"
          >
            <SvgIcon name="refresh" />
          </el-button>
          <el-button
            v-else
            class="!p-2 !m-1"
            type="danger"
            @click="handleChangeStatus(scope.row.id, false)"
          >
            <SvgIcon name="error" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加或修改对话框 -->
    <DialogTemplate :attribute="DialogEnum.ROLE" title="修改角色">
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item label="昵称" prop="name">
          <el-input v-model="form.name" placeholder="请输入" />
        </el-form-item>
        <el-container v-for="(v, k) in permissionMap" direction="vertical">
          <span>{{ k }} 表权限</span>
          <el-form-item prop="permission">
            <el-checkbox-group v-model="permissionForm[k]" @change="permissionChange(k + '')">
              <el-container v-for="p in v" :key="p.toString()">
                <el-checkbox v-if="p.includes('all')" :label="p" :value="p" />
                <el-checkbox v-else :disabled="permissionDisable[k]" :label="p" :value="p" />
              </el-container>
            </el-checkbox-group>
          </el-form-item>
        </el-container>
        <el-container class="flex-wrap">
          <el-form-item label="经验值" prop="experience">
            <el-input-number
              v-model="form.experience"
              :max="2147483647"
              :min="128"
              class="min-w-52"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :value="false">停用</el-radio>
              <el-radio :value="true">启用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-container>
      </el-form>
      <el-container class="justify-between">
        <el-button type="info" @click="systemStore.dialog.role = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </el-container>
    </DialogTemplate>
  </el-container>
</template>
